
export function snapToGrid(canvasX, canvasY) {
  if (isNaN(canvasX) || isNaN(canvasY)) {
    return { x: this.crosshairX, y: this.crosshairY };
  }
  const gridX = (canvasX - this.offsetX) / this.scale;
  const gridY = (canvasY - this.offsetY) / this.scale;
  return {
    x: Math.round(gridX / this.gridSize) * this.gridSize,
    y: Math.round(gridY / this.gridSize) * this.gridSize,
  };
}

export function worldToScreen(pos) {
  return {
      x: pos.x, // 直接使用世界坐标，因为画布已应用变换
      y: pos.y,
    };
}

export function screenToWorld(pos) {
  return {
    x: (pos.x - this.offsetX) / this.scale,
    y: (pos.y - this.offsetY) / this.scale,
  };
}

export function distance(p1, p2) {
  return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
}

export function closestPointOnLine(point, lineStart, lineEnd) {
  const A = point.x - lineStart.x;
  const B = point.y - lineStart.y;
  const C = lineEnd.x - lineStart.x;
  const D = lineEnd.y - lineStart.y;
  const dot = A * C + B * D;
  const len_sq = C * C + D * D;
  let param = -1;
  if (len_sq !== 0) param = dot / len_sq;
  let xx, yy;
  if (param < 0) {
    xx = lineStart.x;
    yy = lineStart.y;
  } else if (param > 1) {
    xx = lineEnd.x;
    yy = lineEnd.y;
  } else {
    xx = lineStart.x + param * C;
    yy = lineStart.y + param * D;
  }
  return {
    point: { x: xx, y: yy },
    distance: Math.sqrt((point.x - xx) ** 2 + (point.y - yy) ** 2),
  };
}

export function snapToWallEndpoint(canvasX, canvasY) {
  const worldPos = screenToWorld.call(this, { x: canvasX, y: canvasY });
  let closest = null;
  let minDistance = Infinity;
  const threshold = 15 / this.scale; // 增加端点吸附阈值
  this.sureRoom.flat().forEach(wall => {
    const startDist = distance(worldPos, wall.start);
    const endDist = distance(worldPos, wall.end);
    if (startDist < minDistance && startDist < threshold) {
      minDistance = startDist;
      closest = wall.start;
    }
    if (endDist < minDistance && endDist < threshold) {
      minDistance = endDist;
      closest = wall.end;
    }
  });
  return closest ? { x: closest.x, y: closest.y } : null;
}
